package com.jastar.android.game.richman.logic.weight;

import java.util.Collection;
import java.util.Optional;
import java.util.Random;

public class WeightSet<W extends WeightAble> {

    private final Random random = new Random(System.currentTimeMillis());
    private final Collection<W> collection;
    private int weightSum;

    public WeightSet(Collection<W> collection) {
        this.collection = collection;

        //初始化权重辅助参数
        weightSum = 0;
        for (W entity : collection) {
            entity.setMin(weightSum);
            entity.setMax(weightSum + entity.getWeight() - 1);
            weightSum += entity.getWeight();
        }
    }

    public W random() {
        int weight = random.nextInt(weightSum);
        Optional<W> item = collection.stream().filter(e -> weight >= e.getMin() && weight <= e.getMax()).findFirst();
        return item.orElseThrow(() -> new RuntimeException("WeightSet.get() exception."));
    }

}
